<?php namespace Common\Model;
use Hdphp\Model\Model;
/**
 * 友情链接模型
 */
class Link extends Model{
		protected $table = 'link';
		//自动验证
		protected $validate = array(
				array('lname','required','名称必须填写哦^_^',3,3),
				array('url','required','Url地址必须填写哦^_^',3,3),
				array('sort','required','排序必须填写哦^_^',3,3),
				array('sort','num:0,65535','排序必须为数字哦^_^',3,3)
				);
		//自动完成
		protected $auto = array(
				array('addtime','time','function',3,1),
				array('logo','up','method',3,3)
				);
		
		//上传logo图片
		protected function up(){
			if ($logoPath = Q('post.logo')) {
					return $logoPath;
			}
			//文件路径
			$imgDir = 'Linkimg/' . date('ymd');
			//上传图片
			$upload = Upload::path($imgDir)->type('jpg,png,gif')->size(2000000)->make();
			//上传成功
			if ($upload) {
				//组合缩略图路径
				$imgPath =  $imgDir . '/' . 'logo_' . $upload['0']['basename'];
				//缩略图处理，进行缩略并保存起来
				$thumbPath = Image::thumb($upload['0']['path'],$imgPath,100,100,6);
				//删除原图
				unlink($upload['0']['path']);
				return $thumbPath;
			}
			return '';
		}
		
		//添加
		public function store(){
			 if (!$this->create()) return false;
			 //上传文件判断 4代表没有选择上传文件
			 if ($_FILES) {
			 	if ($_FILES['logo']['error'] !=4) {
			 		if ($error = Upload::getError()) {
			 			//把上传的错误信息存入到Model的error属性中
			 			$this->error = $error;
			 			return false;
			 		}
			 	}
			 }
			 //添加
			 return $this->add();
		}
		
		//编辑
		public function edit($lid){
			if (!$this->create()) return false;
			//上传文件
			if ($_FILES) {
				if ($_FILES['logo']['error'] !=4) {
					if ($error = Upload::getError()) {
						//把上传的错误信息存入到Model的error属性中
						$this->error = $error;
						return false;
					}
				}
			}
			//删除原图操作
			$logoArr = $this->where(array('lid'=>$lid))->field('logo')->find();
			$logo = Q('post.logo');
			if ($logo != $logoArr['logo']) {
					unlink($logoArr['logo']);
			}
			//修改数据
			return $this->save();
		}
		
		//删除
		public function del($lid){
			$data = $this->where(array('lid' => $lid))->field('logo')->find();
			if ($data['logo']) {
					unlink($data['logo']);
			}
			return $this->delete($lid);
		}
}
?>